package com.icinfo.cloud.provider.punish.execute.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.*;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.common.utils.BusinessContextUtil;
import com.icinfo.cloud.provider.common.utils.HeaderUtil;
import com.icinfo.cloud.provider.common.utils.ParseTextUtil;
import com.icinfo.cloud.provider.punish.approval.vo.LineTerritoryInfoVo;
import com.icinfo.cloud.provider.punish.common.csourcedocumentoperate.mapper.CSourceDocCommonOperateMapper;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.FillAndConvertToPdfRequest;
import com.icinfo.cloud.provider.punish.common.documentoperate.dto.StageDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormDataVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.vo.DocumentCommonFormHtmlVo;
import com.icinfo.cloud.provider.punish.common.nonlitigation.dto.CaseNonLitigationExecuteRequestDto;
import com.icinfo.cloud.provider.punish.common.nonlitigation.service.ICaseNonLitigationExecuteRecordService;
import com.icinfo.cloud.provider.punish.common.seal.dto.FileSealInfoQueryDto;
import com.icinfo.cloud.provider.punish.common.seal.service.IFileSealProvinceUnifiedService;
import com.icinfo.cloud.provider.punish.config.mapper.ConfigBusiParamDocumentColumnMapper;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentColumn;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDeptService;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.config.vo.BusiTableOperateVo;
import com.icinfo.cloud.provider.punish.evideinv.service.EvidenceInventoryService;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocCommonHtmlRequest;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocCommonOperateSaveDto;
import com.icinfo.cloud.provider.punish.execute.enums.ExecuteStateEnum;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteAppendixRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordHisMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteMainInfoMapper;
import com.icinfo.cloud.provider.punish.execute.model.*;
import com.icinfo.cloud.provider.punish.execute.service.*;
import com.icinfo.cloud.provider.punish.execute.vo.ExecutePartyInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.AppendixDto;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandlePersonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseTemporaryRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseDocumentNumberSerialService;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseTemporaryRecordService;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.enums.CaseStatusChangeTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.workflow.config.service.IConfigWorkFlowDocumentService;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.HttpClientUtil;
import com.icinfo.framework.tools.utils.MapUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import com.timevale.tgtext.text.pdf.PdfReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 描述：文书阶段公共操作接口事先类
 *
 * @author xiangyuyu
 * @date 2022/2/16 21:07
 */
@Service
@Slf4j
public class ExecuteDocCommonOperateServiceImpl implements IExecuteDocCommonOperateService {
    @Value("${document.url}")
    private String url;
    @Value("${document.api.templateDetail}")
    private String templateDetail;
    @Value("${document.api.uploadConvertedPdf}")
    private String uploadConvertedPdf;
    @Value("${document.api.uploadBase64File}")
    private String uploadBase64File;
    @Resource
    IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Autowired
    private IExecuteHandlePersonRecordService executeHandlePersonRecordService;
    @Autowired
    private IConfigBusiParamDeptService configBusiParamDeptService;

    @Resource
    private IFileSealProvinceUnifiedService fileSealProvinceUnifiedService;

    @Autowired
    private ICaseDocumentNumberSerialService caseDocumentNumberSerialService;
    @Resource
    ICaseTemporaryRecordService caseTemporaryRecordService;
    @Resource
    private ConfigBusiParamDocumentColumnMapper configBusiParamDocumentColumnMapper;
    @Resource
    private CSourceDocCommonOperateMapper cSourceDocCommonOperateMapper;
    @Autowired
    private IExecutePartyInfoService executePartyInfoService;
    @Autowired
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private ICaseNonLitigationExecuteRecordService caseNonLitigationExecuteRecordService;
    @Resource
    private EvidenceInventoryService evidenceInventoryService;
    @Resource
    private ExecuteMainInfoMapper executeMainInfoMapper;
    @Resource
    private IExecuteMainInfoService executeMainInfoService;
    @Resource
    private IExecuteDocumentRecordService executeDocumentRecordService;
    @Resource
    private ExecuteDocumentRecordMapper executeDocumentRecordMapper;
    @Resource
    private ExecuteDocumentRecordHisMapper executeDocumentRecordHisMapper;
    @Resource
    private ExecuteAppendixRecordMapper executeAppendixRecordMapper;
    @Resource
    private IExecuteAppendixRecordService executeAppendixRecordService;
    @Resource
    private IExecuteFlowRecordService executeFlowRecordService;

    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;


    /**
     * 送达关联且需要当事人id的文书种类编码列表
     */
    public static List<String> sentRelatedNeedPartyIdDocumentKindCodeList;

    @Autowired
    private IConfigWorkFlowDocumentService configWorkFlowDocumentService;


    static {
        sentRelatedNeedPartyIdDocumentKindCodeList = new ArrayList<>();
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDHZ);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZXQKHCJL);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_LHTZS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDDZQRS);
    }

    /**
     * 保存文书信息通用接口
     *
     * @param saveDto
     * @return {@link boolean}
     * @author liyafeng
     * @date 2022/2/27
     */
    @Override
    @Transactional(rollbackFor = {Error.class, Exception.class})
    public Map<String, Object> saveDocInfo(ExecuteDocCommonOperateSaveDto saveDto) {

        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(saveDto.getExecuteId());
        String documentCatalogCode = saveDto.getDocumentCatalogCode();
        String partyId = saveDto.getPartyId();
        //查询文书配置信息
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        saveDto.setDocumentKindCode(documentKindCode);
        Map<String, Object> resultMap = new HashMap<>();
        int num = 0;
        String documentId = "";
        resultMap.put("success", "true");
        //处理参数
        Map<String, Object> paramMap = dealDocParamMap(saveDto);
        long start = System.currentTimeMillis();
        System.out.println("文书生成开始----------------------------------" + start);
        //文号生成;1.判断文号是否已生成 2.未生成则 判断文号生成配置，审批前生成在此处生成，审批后生成在审批完成后生成
        //外部系统对接时使用对应系统文号
        String documentNumber;
        //documentNumber="文书号0001";
        documentNumber = genDocumentNumber(documentCatalogCode, saveDto, configBusiParamDocumentInfo);
        paramMap.put("documentNumber", documentNumber);
        // 处理案件操作变更
        //根据条件添加签章时间
        if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign())) {
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                paramMap.put("sealDate", DateUtils.formatDate(new Date(), "yyyy年MM月dd日"));
            }
        }
        //根据文书目录编码获取模板code
        String templateCode = getTemplateCodeByDocumentCatalogCode(saveDto.getDocumentCatalogCode(), saveDto.getExecuteId(), saveDto.getDataMap());
        //生成未签章文书
        FillAndConvertToPdfRequest pdfRequest = new FillAndConvertToPdfRequest();
        pdfRequest.setTemplateCode(templateCode);
        pdfRequest.setParamMap(saveDto.getDataMap());
        //判断文书模板类型是否为窄幅
        if (DocumentTemplateTypeEnum.NARROW_TEMPLATE.getCode().equals(saveDto.getDocumentTemplateType())) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        //简易处罚决定书设置模板类型为窄幅
        if (DocumentKindEnum.DOC_KIND_JYCXCFJDS.getCode().equals(documentKindCode)) {
            pdfRequest.setTemplateType(DocumentTemplateKindEnum.NARROW_TEMPLATE.getCode());
        }
        Map<String, String> pdfUrl = getConvertedPdfUrl(pdfRequest);
        System.out.println("生成未签章文书耗时------------------------" + (System.currentTimeMillis() - start));
        if (ObjectUtil.isEmpty(pdfUrl)) {
            resultMap.put("success", "false");
            resultMap.put("msg", "文书生成失败！");
            return resultMap;
        }
        //计算送达期限
        String isSend = configBusiParamDocumentInfo.getIsSend();
        LocalDate sentDeadLine = null;
        if (YesOrNoEnum.YES.getCode().equals(isSend)) {
            Integer limitDay = configBusiParamDocumentInfo.getSendLimitDay();
            String limitDayType = configBusiParamDocumentInfo.getSendLimitType();
            sentDeadLine = executeDocumentRecordService.calculateSentDeadLine(executeMainInfo.getExecuteId(), documentCatalogCode, limitDay, limitDayType, false);
            if (ObjectUtils.isEmpty(sentDeadLine)) {
                throw new BusinessException("未获取到文书送达期限-executeId:" + executeMainInfo.getExecuteId() + ",documentCatalogCode:" + documentCatalogCode);
            }
        }
        //判断是否需要签章
        String pdfSealUrl = "";
        String isGetBlankDoc = saveDto.getIsGetBlankDoc();
        String noSealPdfUrl = pdfUrl.get("fileUrl");

        if ("1".equals(configBusiParamDocumentInfo.getIsDeptSign()) && !YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
            //文书签章 1.非审批文书签章 2.审批通过文书签章
            if (("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) || !"1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                FileSealInfoQueryDto queryDto = new FileSealInfoQueryDto();
                queryDto.setFileBase64(pdfUrl.get("fileBase64"));
                pdfSealUrl = dealFileSeal(queryDto);
                if (log.isDebugEnabled()) {
                    log.debug("签章耗时------------------------" + (System.currentTimeMillis() - start));
                }
                if (StringUtils.isBlank(pdfSealUrl)) {
                    resultMap.put("success", "false");
                    resultMap.put("msg", "文书签章失败！");
                    return resultMap;
                }
                Map<String, Object> operateMap = operateExecuteDocumentRecord(saveDto.getDocumentCatalogCode(), executeMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), sentDeadLine);
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
            if (!"CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                //num = operateExecuteDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);

                //从签字捺印过来，原先签章文件是非空的，要保留
                ExecuteDocumentRecord oriRecord = executeDocumentRecordService.getExecuteDocumentRecord(saveDto.getExecuteId(), documentCatalogCode, partyId);
                if (!ObjectUtils.isEmpty(oriRecord) && !ObjectUtils.isEmpty(oriRecord.getDocumentUrlAfterSeal())) {
                    pdfSealUrl = oriRecord.getDocumentUrlAfterSeal();
                }
                //num = operateExecuteDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
                Map<String, Object> operateMap = operateExecuteDocumentRecord(saveDto.getDocumentCatalogCode(), executeMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), sentDeadLine);
                num = MapUtils.getIntValue(operateMap, "num", 0);
                documentId = MapUtils.getString(operateMap, "documentId", "");
            }
        } else {
            //num = operateExecuteDocumentRecord(saveDto.getDocumentCatalogCode(), caseMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, sentDeadLine);
            Map<String, Object> operateMap = operateExecuteDocumentRecord(saveDto.getDocumentCatalogCode(), executeMainInfo, pdfUrl.get("fileUrl"), documentNumber, paramMap, pdfSealUrl, saveDto.getIsMultipleDoc(), saveDto.getBelongDocumentId(), partyId, saveDto.getDocumentTemplateType(), sentDeadLine);
            num = MapUtils.getIntValue(operateMap, "num", 0);
            documentId = MapUtils.getString(operateMap, "documentId", "");
        }
        //操作文书记录表 判断文书记录是否存在，存在则添加历史表，然后更新数据
        if (num < 1) {
            resultMap.put("success", "false");
            resultMap.put("msg", "保存失败！");
            return resultMap;
        }
        //送达回证特殊处理
        String receiptDocUrl = pdfSealUrl;
        if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
            //空白送达回证无需签章
            receiptDocUrl = noSealPdfUrl;
        } else {
            receiptDocUrl = pdfSealUrl;
        }
        updateDocumentRecordInfoAfterSentReceiptPrint(documentCatalogCode, pdfUrl, receiptDocUrl, saveDto.getExecuteId(), isGetBlankDoc, partyId);
        System.out.println("送达回证特殊处理耗时------------------------" + (System.currentTimeMillis() - start));
        resultMap.put("documentId", documentId);
        resultMap.put("documentCatalogCode", documentCatalogCode);

        //送达方式及地址确认书
        if (!YesOrNoEnum.NO.getCode().equals(saveDto.getIsUpdateRelationTable())) {
            operateBusiTableByDocumentCatalogCode(saveDto);
        }
        if ("ZXQKHCJL".equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            //处理文书关联的附件信息
            //dealDocAppendix( executeMainInfo, saveDto,configBusiParamDocumentInfo);
            //执行情况核查记录-文书生成 -修改为结案阶段
            updateExecuteStage(executeMainInfo, executeMainInfo.getExecuteState(), ExecuteStateEnum.CASE_CLOSED.getCode());
        } else if ("QZZXGG".equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            //处理文书关联的附件信息
            dealDocAppendix(executeMainInfo, saveDto, configBusiParamDocumentInfo);
            //执行情况核查记录-文书生成 -跳转到结案阶段
            updateExecuteStage(executeMainInfo, executeMainInfo.getExecuteState(), ExecuteStateEnum.ENFORCE.getCode());
        } else if ("QZZXGG".equals(configBusiParamDocumentInfo.getDocumentKindCode()) && "CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal())) {//执行情况核查记录-文书生成 -跳转到结案阶段
            updateExecuteStage(executeMainInfo, executeMainInfo.getExecuteState(), null);
        }

        // 证据库案件信息同步对接
        try {
            String la = "LASPB";
            if (saveDto.getDocumentCatalogCode().contains(la) && StringUtils.isNotBlank(documentNumber)) {
                // 换为证据库新API
                evidenceInventoryService.saveEvent(saveDto.getExecuteId(), documentNumber);
            }
        } catch (Exception e) {
            log.info("证据库立案对接失败:{}", e.getMessage());
        }
        return resultMap;
    }

    //更改裁执分离阶段,添加阶段流转日志
    private void updateExecuteStage(ExecuteMainInfo executeMainInfo, String currentStageCode, String nextStageCode) {
        //修改主表阶段信息
        executeMainInfo.setExecuteState(nextStageCode);
        Example executeMainInfoUpdateExample = new Example(ExecuteMainInfo.class);
        executeMainInfoUpdateExample.createCriteria().andEqualTo("executeId", executeMainInfo.getExecuteId());
        executeMainInfoMapper.updateByExample(executeMainInfo, executeMainInfoUpdateExample);
        //添加阶段流转日志
        executeFlowRecordService.dealCurrentAndNextExecuteFlowRecord(executeMainInfo.getExecuteId(), currentStageCode, nextStageCode);
    }

    private void dealDocAppendix(ExecuteMainInfo executeMainInfo, ExecuteDocCommonOperateSaveDto saveDto,
                                 ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        if (ObjectUtil.isNotEmpty(saveDto.getAppendixList()) && saveDto.getAppendixList().size() > 0) {
            List<AppendixDto> list = saveDto.getAppendixList();
            // 先删除
            Example example1 = new Example(ExecuteAppendixRecord.class);
            example1.createCriteria().andEqualTo("documentCatalogCode", configBusiParamDocumentInfo.getDocumentCatalogCode())
                    .andEqualTo("executeStageCode", executeMainInfo.getExecuteState()).andEqualTo("executeId", executeMainInfo.getExecuteId());
            executeAppendixRecordMapper.deleteByExample(example1);
            for (int i = 0; i < list.size(); i++) {
                ExecuteAppendixRecord record = new ExecuteAppendixRecord();
                record.setExecuteId(executeMainInfo.getExecuteId());
                record.setExecuteStageCode(executeMainInfo.getExecuteState());
                record.setExecuteStageName(ExecuteStateEnum.getValueByCode(executeMainInfo.getExecuteState()));
                record.setDocumentCatalogCode(configBusiParamDocumentInfo.getDocumentCatalogCode());
                record.setAppendixUrl(list.get(i).getAppendixUrl());
                record.setAppendixTypeId(list.get(i).getAppendixTypeId());
                record.setAppendixName(list.get(i).getAppendixName());
                executeAppendixRecordService.saveExecuteAppendixRecord(record);
            }
        }
    }

    /**
     * 根据条件生成文号
     *
     * @param saveDto
     * @param configBusiParamDocumentInfo
     * @return {@link String}
     * @author liyafeng
     * @date 2022/3/12
     */
    private String genDocumentNumber(String documentCatalogCode, ExecuteDocCommonOperateSaveDto saveDto, ConfigBusiParamDocumentInfo configBusiParamDocumentInfo) {
        String documentNumber = "";
        //判断文号是否已生成
        ExecuteDocumentRecord executeDocumentRecord = null;
        if (StringUtils.isBlank(saveDto.getIsMultipleDoc()) || Constant.STRING_0.equals(saveDto.getIsMultipleDoc())) {
            executeDocumentRecord = executeDocumentRecordService.getExecuteDocumentRecord(saveDto.getExecuteId(), documentCatalogCode, saveDto.getPartyId());
        }
        if (StringUtils.isNotBlank(saveDto.getIsMultipleDoc()) && Constant.STRING_1.equals(saveDto.getIsMultipleDoc()) && StringUtils.isNotBlank(saveDto.getBelongDocumentId())) {
            executeDocumentRecord = executeDocumentRecordMapper.selectByPrimaryKey(saveDto.getBelongDocumentId());
        }
        if (null != executeDocumentRecord && StringUtils.isNotBlank(executeDocumentRecord.getDocumentNumber())) {
            documentNumber = executeDocumentRecord.getDocumentNumber();
            return documentNumber;
        }
        String docNoGene = configBusiParamDocumentInfo.getDocNoGene();
        if ("1".equals(docNoGene)) {
            //审批前
            documentNumber = getDocumentNumber(saveDto.getExecuteId(), documentCatalogCode);
        } else if ("CLOSE-TRIGGER-APPROVAL-PASS".equals(saveDto.getCloseSignal()) && "1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            //审批完成后
            documentNumber = getDocumentNumber(saveDto.getExecuteId(), documentCatalogCode);
        } else if (Constant.STRING_1.equals(configBusiParamDocumentInfo.getIsGenDocnum())) {
            documentNumber = getDocumentNumber(saveDto.getExecuteId(), documentCatalogCode);
        }
        return documentNumber;
    }

    /**
     * 描述：送达回证打印后更新文书记录信息
     *
     * @param documentCatalogCode 文书目录编码
     * @param pdfUrl              送达回证文书pdf信息
     * @param pdfSealUrl          签章后送达回证文书pdf信息
     * @param caseId              案件id
     * @param isGetBlankDoc       是否获取空白文书
     * @param partyId             当事人id
     * @author xiangyuyu
     * @date 2022-03-12 16:00
     */
    private void updateDocumentRecordInfoAfterSentReceiptPrint(String documentCatalogCode, Map<String, String> pdfUrl, String pdfSealUrl, String caseId, String isGetBlankDoc, String partyId) {
        //先校验文书是否为送达回证
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo
                = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtils.isEmpty(configBusiParamDocumentInfo)) {
            throw new BusinessException("非法的文书目录编码：" + documentCatalogCode);
        }
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if (Constant.STRING_KIND_CODE_SDHZ.equals(documentKindCode)) {
            String sentReceiptPdfUrl = "";
            if (!ObjectUtils.isEmpty(pdfSealUrl)) {
                sentReceiptPdfUrl = pdfSealUrl;
            } else {
                if (ObjectUtils.isEmpty(pdfUrl) || pdfUrl.size() == 0) {
                } else {
                    sentReceiptPdfUrl = pdfUrl.get("fileUrl");
                    if (ObjectUtils.isEmpty(sentReceiptPdfUrl)) {
                        log.error("未找到送达回证文书pdf地址为空");
                    }
                }
            }
            //获取xx送达回证的文书记录
            ExecuteDocumentRecord executeDocumentRecord = executeDocumentRecordService.getExecuteDocumentRecord(caseId, documentCatalogCode, partyId);
            if (!ObjectUtils.isEmpty(executeDocumentRecord)) {
                ExecuteDocumentRecord newRecord = new ExecuteDocumentRecord();
                newRecord.setId(executeDocumentRecord.getId());
                if (YesOrNoEnum.YES.getCode().equals(isGetBlankDoc)) {
                    newRecord.setDocumentUrlBlank(sentReceiptPdfUrl);
                } else {
                    newRecord.setDocumentUrl(sentReceiptPdfUrl);
                }
                executeDocumentRecordMapper.updateByPrimaryKeySelective(newRecord);
            }
        }
    }

    /**
     * 描述：强制执行申请书生成后发送至法院非诉执行立案申请
     *
     * @param saveDto 保存dto
     * @author shishengyao
     * @date 2022/04/10
     */
    private void nonLitigationExecute(StageDocCommonOperateSaveDto saveDto) {
        if ("QZZXSQS".equals(saveDto.getDocumentKindCode())) {
            CaseNonLitigationExecuteRequestDto requestDto = new CaseNonLitigationExecuteRequestDto();
            requestDto.setCaseId(saveDto.getCaseId());
            Map<String, Object> result = caseNonLitigationExecuteRecordService.nonLitigationExecuteRegister(requestDto);
            if (Constant.STRING_FAIL_EN.equals(result.get("code"))) {
                throw new BusinessException(result.get("errorMsg").toString());
            }
        }
    }

    /**
     * 根据配置更新相关数据
     *
     * @param saveDto
     * @return
     * @author wuzhihui
     * @date 2022/9/11
     */
    private void operateBusiTableByDocumentCatalogCode(ExecuteDocCommonOperateSaveDto saveDto) {
        List<BusiTableOperateVo> busiTableOperateVoList = configBusiParamDocumentColumnMapper.selectTableNameListByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        if (null != busiTableOperateVoList && busiTableOperateVoList.size() > 0) {
            for (BusiTableOperateVo busiTableOperateVo : busiTableOperateVoList) {
                Example example = new Example(ConfigBusiParamDocumentColumn.class);
                example.createCriteria().andEqualTo("documentCatalogCode", saveDto.getDocumentCatalogCode()).andEqualTo("busiTableNameEn", busiTableOperateVo.getBusiTableNameEn()).andEqualTo("busiOperateType", busiTableOperateVo.getBusiOperateType());
                List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList = configBusiParamDocumentColumnMapper.selectByExample(example);
                if ("U".equals(busiTableOperateVo.getBusiOperateType())) {
                    updateBusiTable(busiTableOperateVo, busiTableOperateVoList, saveDto, configBusiParamDocumentColumnList);
                }
                if ("I,U".equals(busiTableOperateVo.getBusiOperateType())) {
                    //先判断是否存在
                    String selectSql = "select count(1) from upcase." + busiTableOperateVo.getBusiTableNameEn() + " where case_id='" + saveDto.getExecuteId() + "'";
                    ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
                    String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
                    if (Constant.STRING_KIND_CODE_SDDZQRS.equals(documentKindCode)) {
                        selectSql = selectSql.concat(" and party_id = '" + saveDto.getPartyId() + "'");
                    }
                    if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(documentKindCode)) {
                        selectSql = selectSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(documentKindCode).getCode() + "'");
                    }
                    int num = configBusiParamDocumentColumnMapper.executeSelectNumSql(selectSql);
                    if (num > 0) {
                        //存在则更新
                        updateBusiTable(busiTableOperateVo, busiTableOperateVoList, saveDto, configBusiParamDocumentColumnList);

                    } else {
                        //不存在则插入
                        Map<String, String> insertMap = new HashMap<>();
                        //组装map
                        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
                            if ("id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), StringUtils.uuid());
                                continue;
                            }
                            if ("case_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getExecuteId());
                                continue;
                            }
                            if ("document_catalog_code".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getDocumentCatalogCode());
                                continue;
                            }
                            if ("create_time".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
                                continue;
                            }
                            //---送达方式及地址确认书使用start---
                            if ("party_id".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), saveDto.getPartyId());
                                continue;
                            }
                            /*if ("status".equals(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                                insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), null);//默认设置为空，签字确认后修改为1
                                continue;
                            }*/
                            //---送达方式及地址确认书使用end---

                            String columnValue = "";
                            try {
                                //columnValue = saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()).toString();
                                columnValue = MapUtils.getString(saveDto.getDataMap(), configBusiParamDocumentColumn.getDocumentTemplateFieldEn(), "");
                            } catch (Exception e) {
                                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
                            }
                            insertMap.put(configBusiParamDocumentColumn.getBusiColumnEn(), columnValue);
                        }
                        //生成INSERT INTO table(field1,field2) 部分
                        StringBuffer sbField = new StringBuffer();
                        //生成VALUES('value1','value2') 部分
                        StringBuffer sbValue = new StringBuffer();
                        sbField.append("INSERT INTO  upcase." + busiTableOperateVo.getBusiTableNameEn() + "(");
                        for (Map.Entry<String, String> entry : insertMap.entrySet()) {
                            String mapKey = entry.getKey();
                            String mapValue = entry.getValue();
                            mapValue = mapValue.replace("'", "''");
                            sbField.append(mapKey + ",");
                            sbValue.append("'" + mapValue + "',");
                        }
                        sbField = sbField.deleteCharAt(sbField.length() - 1);
                        sbValue = sbValue.deleteCharAt(sbValue.length() - 1);
                        String insertSql = sbField.toString() + ") VALUES(" + sbValue.toString() + ")";
                        configBusiParamDocumentColumnMapper.executeInsertSql(insertSql);
                    }


                }
            }
        }
    }

    /**
     * 更新操作
     *
     * @param busiTableOperateVo
     * @param busiTableOperateVoList
     * @param saveDto
     * @param configBusiParamDocumentColumnList
     * @return
     * @author liyafeng
     * @date 2022/3/11
     */
    private void updateBusiTable(BusiTableOperateVo busiTableOperateVo, List<BusiTableOperateVo> busiTableOperateVoList, ExecuteDocCommonOperateSaveDto saveDto, List<ConfigBusiParamDocumentColumn> configBusiParamDocumentColumnList) {
        String tableName = busiTableOperateVo.getBusiTableNameEn();
        String caseId = saveDto.getExecuteId();
        String setSql = "";
        for (ConfigBusiParamDocumentColumn configBusiParamDocumentColumn : configBusiParamDocumentColumnList) {
            //BusiOperateCondition 不为空 此字段不更新
            if (StringUtils.isNotBlank(configBusiParamDocumentColumn.getBusiOperateCondition())) {
                continue;
            }
            String columnValue = "";
            try {
                columnValue = saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()).toString();
                columnValue = columnValue.replace("'", "''");
            } catch (Exception e) {
                //前端没有传key值，此字段不更新
                if (saveDto.getDataMap().get(configBusiParamDocumentColumn.getDocumentTemplateFieldEn()) == null) {
                    continue;
                }
                throw new BusinessException(configBusiParamDocumentColumn.getDocumentTemplateFieldCn() + "为空");
            }
            if (StringUtils.isBlank(setSql)) {
                setSql = configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            } else {
                setSql = setSql + "," + configBusiParamDocumentColumn.getBusiColumnEn() + "='" + columnValue + "'";
            }
        }
        String updateSql = "update upcase." + tableName + " set " + setSql + " where " + " case_id='" + caseId + "'";

        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(saveDto.getDocumentCatalogCode());
        if (Constant.STRING_KIND_CODE_SDDZQRS.equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and party_id = '" + saveDto.getPartyId() + "'");
        }
        //案件操作文书
        if (CaseStatusChangeTypeEnum.isCaseChangeDocEnum(configBusiParamDocumentInfo.getDocumentKindCode())) {
            updateSql = updateSql.concat(" and case_change_type = '" + CaseStatusChangeTypeEnum.getEnumByDocumentKindCode(configBusiParamDocumentInfo.getDocumentKindCode()).getCode() + "'");
        }
        configBusiParamDocumentColumnMapper.executeUpdateSql(updateSql);
    }


    /**
     * 根据文书目录编码获取法人或个人文件模板code
     *
     * @param documentCatalogCode
     * @return {@link String}
     * @author liyafeng
     * @date 2022/3/1
     */
    @Override
    public String getTemplateCodeByDocumentCatalogCode(String documentCatalogCode, String caseSourceId, Map<String, Object> paramMap) {
        String templateCode = "";
        ConfigBusiParamDocumentInfo detailResult = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        if (ObjectUtil.isNotEmpty(detailResult)) {
            //根据当事人类型获取对应的模板
            List<ExecutePartyInfoVo> executePartyInfos = executePartyInfoService.getExecutePartyInfo(caseSourceId);
            if (null != executePartyInfos && executePartyInfos.size() > 0) {
                ExecutePartyInfoVo executePartyInfoVo = executePartyInfos.get(0);
                if ("1".equals(executePartyInfoVo.getPartyType())) {
                    //个人
                    templateCode = detailResult.getTemplatePersonCode();
                } else {
                    //法人
                    templateCode = detailResult.getTemplateLegalCode();
                }
            } else {
                //个人
                templateCode = detailResult.getTemplatePersonCode();
            }
        }
        return templateCode;
    }

    /**
     * 操作文书记录表
     *
     * @param documentCatalogCode  文件目录的代码
     * @param executeMainInfo
     * @param convertedPdfUrl
     * @param documentNumber
     * @param paramMap
     * @param pdfSealUrl           pdf印网址
     * @param isMultipleDoc
     * @param partyId              当事人id
     * @param documentTemplateType 文书模板类型
     * @return int
     * @author shishengyao
     * //* @date 2022/03/14
     */
    private Map<String, Object> operateExecuteDocumentRecord(String documentCatalogCode, ExecuteMainInfo executeMainInfo,
                                                             String convertedPdfUrl, String documentNumber, Map<String, Object> paramMap, String pdfSealUrl,
                                                             String isMultipleDoc, String belongDocumentId, String partyId, String documentTemplateType, LocalDate sentDeadline) {

        //String handleType = caseMainInfo.getHandleType();
        Map<String, Object> operateMap = new HashMap<>();
        //根据目录编码查询
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        int num = 0;
        UserDTO userDTO = null;
        try {
            userDTO = UserUtil.getUserInfo();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (ObjectUtils.isEmpty(userDTO)) {
            userDTO = new UserDTO();
            userDTO.setUserId(0L);
            userDTO.setRealName("系统");
        }
        //判断文书记录是否存在
        Example example = new Example(ExecuteDocumentRecord.class);
        Example.Criteria c = example.createCriteria();
        boolean isNeedPartyIdInfo = false;
        if (sentRelatedNeedPartyIdDocumentKindCodeList.contains(documentKindCode)) {
            isNeedPartyIdInfo = true;
        }
        if (StringUtils.isBlank(isMultipleDoc) || Constant.STRING_0.equals(isMultipleDoc) || StringUtils.isBlank(belongDocumentId)) {
            if (DocumentKindEnum.DOC_KIND_LASPB.getCode().equals(configBusiParamDocumentInfo.getDocumentKindCode())) {
                c.andEqualTo("executeId", executeMainInfo.getExecuteId()).andEqualTo("documentCatalogCode", documentCatalogCode);
            } else {
                //非多条文书记录
                c.andEqualTo("executeId", executeMainInfo.getExecuteId()).andEqualTo("documentCatalogCode", documentCatalogCode);
                if (!ObjectUtils.isEmpty(partyId)) {
                    if (isNeedPartyIdInfo) {
                        c.andEqualTo("partyId", partyId);
                    }
                }
            }
        } else if (StringUtils.isNotBlank(belongDocumentId)) {
            c.andEqualTo("executeId", executeMainInfo.getExecuteId()).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("id", belongDocumentId);
        }
        //c.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
        c.andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(example);
        if ((StringUtils.isBlank(isMultipleDoc) || Constant.STRING_0.equals(isMultipleDoc)) || (StringUtils.isNotBlank(belongDocumentId) && Constant.STRING_1.equals(isMultipleDoc))) {
            // 特殊处理中止审批表
            boolean suspendUpdateFlag = true;
            if (null != executeDocumentRecords && executeDocumentRecords.size() > 0 && suspendUpdateFlag) {
                //不为空，则添加历史，更新记录
                for (ExecuteDocumentRecord executeDocumentRecord : executeDocumentRecords) {
                    //添加历史
                    //todo
                    ExecuteDocumentRecordHis executeDocumentRecordHis = new ExecuteDocumentRecordHis();
                    BeanUtils.copyProperties(executeDocumentRecord, executeDocumentRecordHis);
                    executeDocumentRecordHis.setId(StringUtils.uuid());
                    executeDocumentRecordHis.setRecordId(executeDocumentRecord.getId());
                    executeDocumentRecordHis.setOp("update");
                    executeDocumentRecordHis.setHisCreateTime(new Date());
                    executeDocumentRecordHisMapper.insert(executeDocumentRecordHis);
                    //更新文书记录表
                    ExecuteDocumentRecord updateExecuteDocumentRecord = new ExecuteDocumentRecord();
                    updateExecuteDocumentRecord.setId(executeDocumentRecord.getId());
                    updateExecuteDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
                    updateExecuteDocumentRecord.setDocumentUrl(convertedPdfUrl);
                    updateExecuteDocumentRecord.setExecuteId(executeMainInfo.getExecuteId());

                    //updateExecuteDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                    //updateCaseDocumentRecord.setDocumentApprovalStatus(saveDto.getDocumentApprovalStatus());
                    updateExecuteDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                    updateExecuteDocumentRecord.setSentDeadline(sentDeadline);
                    updateExecuteDocumentRecord.setDocumentNumber(documentNumber);
                    updateExecuteDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());

                    updateExecuteDocumentRecord.setPartyId(partyId);//设置当事人id
                    updateExecuteDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
                    if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
                        updateExecuteDocumentRecord.setDocumentTemplateType(documentTemplateType);
                    }
                    updateExecuteDocumentRecord.setCreateUserName(userDTO.getRealName());
                    updateExecuteDocumentRecord.setCreateUserId(userDTO.getUserId().toString());

                    //送达地址确认书,询问通知书及责令改正通知书更新后需重新签字确认
                    if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(documentKindCode)
                            || DocumentKindEnum.DOC_KIND_XWTZS.getCode().equals(documentKindCode)
                            || DocumentKindEnum.DOC_KIND_ZLGZTZS.getCode().equals(documentKindCode)) {
                        //设置待确认
                        updateExecuteDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                        updateExecuteDocumentRecord.setDocumentUrlAfterSign(null);
                        updateExecuteDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                        //设置签署文书为删除状态
                        Example appendixExample = new Example(ExecuteAppendixRecord.class);
                        appendixExample.createCriteria().andEqualTo("executeId", updateExecuteDocumentRecord.getExecuteId())
                                .andEqualTo("documentCatalogCode", updateExecuteDocumentRecord.getDocumentCatalogCode())
                                .andEqualTo("isDelete", "0").andEqualTo("appendixStatus", "1")
                                .andEqualTo("partyId", updateExecuteDocumentRecord.getPartyId());
                        List<ExecuteAppendixRecord> caseAppendixRecords = executeAppendixRecordMapper.selectByExample(appendixExample);
                        if (!ObjectUtils.isEmpty(caseAppendixRecords)) {
                            caseAppendixRecords.forEach(e -> {
                                e.setIsDelete(Constant.STRING_1);
                                executeAppendixRecordMapper.updateByPrimaryKeySelective(e);
                            });
                        }
                        //送达地址确认书需修改送达记录为失效状态
                        if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(documentKindCode)) {
                            Example queryExample = new Example(CaseDocumentSendinfoConfirm.class);
                            queryExample.createCriteria().andEqualTo("caseId", executeMainInfo.getExecuteId())
                                    .andEqualTo("partyId", executeDocumentRecord.getPartyId())
                                    .andEqualTo("status", Constant.INTEGER_1);
                            List<CaseDocumentSendinfoConfirm> sendInfoConfirmList
                                    = caseDocumentSendinfoConfirmMapper.selectByExample(queryExample);
                            if (!ObjectUtils.isEmpty(sendInfoConfirmList)) {
                                for (CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm : sendInfoConfirmList) {
                                    caseDocumentSendinfoConfirm.setStatus(null);
                                    caseDocumentSendinfoConfirmMapper.updateByPrimaryKey(caseDocumentSendinfoConfirm);
                                }
                            }
                        }
                    }

                    num = executeDocumentRecordMapper.updateByPrimaryKeySelective(updateExecuteDocumentRecord);

                    operateMap.put("num", num);
                    operateMap.put("documentId", executeDocumentRecord.getId());
                }
                return operateMap;
            } else {
                ExecuteDocumentRecord executeDocumentRecord = new ExecuteDocumentRecord();
                executeDocumentRecord.setExecuteStageCode(executeMainInfo.getExecuteState());
                executeDocumentRecord.setExecuteStageName(ExecuteStateEnum.getValueByCode(executeMainInfo.getExecuteState()));
                executeDocumentRecord.setExecuteId(executeMainInfo.getExecuteId());
                executeDocumentRecord.setId(StringUtils.uuid());
                executeDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
                executeDocumentRecord.setDocumentUrl(convertedPdfUrl);
                executeDocumentRecord.setSentDeadline(sentDeadline);
                executeDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                executeDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
                //生成默认待提交状态
                if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
                    executeDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
                    executeDocumentRecord.setDocumentAuditStatus("notSubmit");
                }
                if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
                    executeDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
                }
                if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
                    executeDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
                }
                executeDocumentRecord.setDocumentNumber(documentNumber);
                executeDocumentRecord.setCreateUserName(userDTO.getRealName());
                executeDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
                executeDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
                executeDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
                if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
                    executeDocumentRecord.setDocumentTemplateType(documentTemplateType);
                }
                if (!ObjectUtils.isEmpty(partyId)) {
                    //设置当事人id
                    executeDocumentRecord.setPartyId(partyId);
                }
                num = executeDocumentRecordMapper.insert(executeDocumentRecord);
                operateMap.put("num", num);
                operateMap.put("documentId", executeDocumentRecord.getId());
                return operateMap;
            }
        }
        ExecuteDocumentRecord executeDocumentRecord = new ExecuteDocumentRecord();
        executeDocumentRecord.setExecuteId(executeMainInfo.getExecuteId());
        executeDocumentRecord.setId(StringUtils.uuid());
        executeDocumentRecord.setDocumentCatalogCode(documentCatalogCode);
        executeDocumentRecord.setDocumentUrl(convertedPdfUrl);
        executeDocumentRecord.setSentDeadline(sentDeadline);
        executeDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
        executeDocumentRecord.setDocumentContent(JSONObject.toJSON(paramMap).toString());
        //生成默认待提交状态
        if ("1".equals(configBusiParamDocumentInfo.getIsApprove())) {
            executeDocumentRecord.setDocumentApprovalStatus(DocumentStatusEnum.WAIT_TO_SUBMIT.getCode());
            executeDocumentRecord.setDocumentAuditStatus("notSubmit");
        }
        if ("1".equals(configBusiParamDocumentInfo.getIsSend())) {
            executeDocumentRecord.setDocumentSentStatus(DocumentStatusEnum.WAIT_TO_SEND.getCode());
        }
        if (BusinessContextUtil.documentNeedConfirm(configBusiParamDocumentInfo)) {
            executeDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.WAIT_TO_CONFIRM.getCode());
        }
        executeDocumentRecord.setDocumentNumber(documentNumber);
        executeDocumentRecord.setCreateUserName(userDTO.getRealName());
        executeDocumentRecord.setCreateUserId(userDTO.getUserId().toString());
        executeDocumentRecord.setDocumentUrlAfterSeal(pdfSealUrl);
        executeDocumentRecord.setDocumentRecordStatus(DocumentRecordStatusEnum.NORMAL.getCode());//设置文书为正常状态
        if (!ObjectUtils.isEmpty(partyId)) {
            //设置当事人id
            executeDocumentRecord.setPartyId(partyId);
        }
        if (!ObjectUtils.isEmpty(documentTemplateType)) { //设置模板类型
            executeDocumentRecord.setDocumentTemplateType(documentTemplateType);
        }
        num = executeDocumentRecordMapper.insert(executeDocumentRecord);

        operateMap.put("num", num);
        operateMap.put("documentId", executeDocumentRecord.getId());
        return operateMap;
    }

    /**
     * 获取文书html和配置字段公共方法
     *
     * @param request
     * @return {@link Result< String>}
     * @author liyafeng
     * @date 2022/2/18
     */
    @Override
    public DocumentCommonFormHtmlVo getDocumentFormHtml(ExecuteDocCommonHtmlRequest request) {
        DocumentCommonFormHtmlVo vo = new DocumentCommonFormHtmlVo();
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getExecuteId(), null);
        Map<String, Object> objectMap = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
        vo.setHtmlContent(templateDetail.get("htmlContent") == null ? "" : templateDetail.get("htmlContent").toString());
        vo.setTemplateConfigMap(objectMap);
        return vo;
    }

    @Override
    public DocumentCommonFormDataVo getCommonDocumentFormData(ExecuteDocCommonHtmlRequest request) {
        DocumentCommonFormDataVo vo = new DocumentCommonFormDataVo();
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getExecuteId(), null);
        Map<String, Object> resultData = new HashMap<>();
        //查询历史记录
        ExecuteDocumentRecord recordInfo = executeDocumentRecordService.getExecuteDocumentRecord(request.getExecuteId(), request.getDocumentCatalogCode(), request.getPartyId());
        if (ObjectUtil.isNotEmpty(recordInfo) && ObjectUtil.isNotEmpty(recordInfo.getDocumentContent())) {
            String documentContent = "";
            ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(request.getDocumentCatalogCode());
            String documentKindCode = configBusiParamDocumentInfo.getDocumentKindCode();
            documentContent = recordInfo.getDocumentContent();
            resultData = JSON.parseObject(documentContent);
            vo.setOperateType(RecordSaveTypeEnum.MOD.getCode());
        } else {
            //查询是否 有暂存
            CaseTemporaryRecord record = caseTemporaryRecordService.getRecord(request.getExecuteId(), request.getDocumentCatalogCode(), request.getPartyId());
            if (record != null) {
                JSONObject json = JSONObject.parseObject(record.getContent());
                vo.setDataMap(json.getJSONObject("dataMap"));
                vo.setOperateType(RecordSaveTypeEnum.TEMP.getCode());
                return vo;
            }

            //初次获取数据
            dealCommonDocumentFormData(request, resultData);
            //暂存end
            vo.setOperateType(RecordSaveTypeEnum.ADD.getCode());

        }
        vo.setDataMap(resultData);
        return vo;
    }


    private void dealCommonDocumentFormData(ExecuteDocCommonHtmlRequest request, Map<String, Object> resultData) {
        Map<String, Object> templateDetail = getTemplateDetail(request.getDocumentCatalogCode(), request.getExecuteId(), null);
        //根据表名，分组查询所需字段数据，放入一个map中
        Map<String, Object> sourceFieldInfos = JSON.parseObject(templateDetail.get("sourceFieldInfos").toString());
        // 从表中获取数据
        Map<String, String> sourceDataMap = getSourceDataMap(sourceFieldInfos, request);
        if (request.getDocumentCatalogCode().startsWith("QZZXGG")) {
            //强制执行公告-读取强制执行通知填写的裁定结论
            Example example = new Example(ExecuteDocumentRecord.class);
            example.createCriteria().andLike("documentCatalogCode", "QZZXTZS%").
                    andEqualTo("executeId", request.getExecuteId()).
                    andEqualTo("documentRecordStatus", DocumentRecordStatusEnum.NORMAL.getCode());
            List<ExecuteDocumentRecord> qzzxtzsList = executeDocumentRecordMapper.selectByExample(example);
            if (qzzxtzsList != null && qzzxtzsList.size() > 0) {
                String content = qzzxtzsList.get(0).getDocumentContent();
                JSONObject jsonObject = JSONObject.parseObject(content);
                String executeContent = jsonObject.getString("executeContent");
                //设定为裁定结论
                sourceDataMap.put("CDJL", executeContent);
            }
        }
        Map templateFieldConfigs = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
        Set<String> templateConfigSet = templateFieldConfigs.keySet();
        //循环给自动填充的字段赋值
        for (String configKey : templateConfigSet) {
            String value = "";
            JSONObject paramMap = JSON.parseObject(templateFieldConfigs.get(configKey).toString());
            if (ObjectUtil.isNotEmpty(paramMap.get("isAutoData")) && Constant.WHETHER_STRING_YES.equals(paramMap.get("isAutoData"))) {
                String dataGenerateRule = paramMap.getString("dataGenerateRule");
                //自动数据来源，SOURCE_ARTIFICIAL页面填充，SOURCE_SYSTEM系统字段
                if ("SOURCE_ARTIFICIAL".equals(paramMap.getString("autoDataSource"))) {
                    value = dataGenerateRule;
                } else if ("SOURCE_SYSTEM".equals(paramMap.getString("autoDataSource"))) {
                    //组装参数结果
                    value = ParseTextUtil.parseText(dataGenerateRule, sourceDataMap);
                    //格式化日期控件
                    if ("3".equals(paramMap.get("controlType"))) {
                        //日期格式 date ，时间time，日期时间datetime  "timeShow":"yyyy年MM月dd日 hh时mm分ss秒"
                        JSONObject dateConfig = paramMap.getJSONObject("controlConfigContent");
                        String pickerType = dateConfig.getString("pickerType");
                        String timeShow = dateConfig.getString("timeShow");
                        SimpleDateFormat df;
                        if (value.length() > 10) {
                            df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        } else {
                            df = new SimpleDateFormat("yyyy-MM-dd");
                        }
                        try {
                            Date parse = df.parse(value);
                            if ("date".equals(pickerType)) {
                                timeShow = timeShow.substring(0, 11);
                            } else if ("time".equals(pickerType)) {
                                timeShow = timeShow.substring(12, 21);
                            }
                            SimpleDateFormat sdf = new SimpleDateFormat(timeShow);
                            String dateString = sdf.format(parse);
                            value = dateString;
                        } catch (ParseException e) {
                            log.info("日期转换失败：{}", e.getMessage());
                        }
                    } else if ("SOURCE_SYSTEM_List".equals(paramMap.getString("autoDataSource"))) {

                    }
                }
                resultData.put(paramMap.getString("templateFieldEn"), value);
            }
            // 控件类型是签名 获取执法人员签名
            if (ObjectUtil.isNotEmpty(paramMap.getString("controlType"))) {

            }
            if ("CDJL".equals(configKey) && request.getDocumentCatalogCode().startsWith("QZZXGG")) {
                resultData.put("CDJL", sourceDataMap.get("CDJL"));
            }
        }
    }

    /**
     * 根据模板字段配置信息，组装查询所需要的字段，并组装成map格式
     *
     * @param sourceFieldInfos 源字段信息
     * @param request          请求
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/02/28
     */
    private Map<String, String> getSourceDataMap(Map<String, Object> sourceFieldInfos, ExecuteDocCommonHtmlRequest request) {
        Map<String, String> sourceDataMap = new HashMap<>();
        Set<String> keySet = sourceFieldInfos.keySet();
        for (String tableName : keySet) {
            List<String> fieldList = JSONObject.parseArray(sourceFieldInfos.get(tableName).toString(), String.class);
            String fieldSql = StringUtils.join(fieldList, ",");
            String conditionSql = "";
            String whereSql = "execute_id=" + "'" + request.getExecuteId() + "'";
            if ("execute_main_info".equals(tableName)) {
                conditionSql = " from execute." + tableName;
                whereSql = "execute_id=" + "'" + request.getExecuteId() + "'";
            } else if ("execute_party_info".equals(tableName)) {
                //当事人信息
                List<String> packFieldList = new ArrayList<>();
                for (String field : fieldList) {
                    String packField = " string_agg ( " + field + ", '、' order by party_type desc ) as " + field;
                    packFieldList.add(packField);
                }
                fieldSql = StringUtils.join(packFieldList, ",");
                conditionSql = " from execute." + tableName + " cpr ";
                whereSql = "cpr.execute_id=" + "'" + request.getExecuteId() + "'";
                if (!ObjectUtils.isEmpty(request.getPartyId())) {
                    whereSql = whereSql.concat(" and cpr.id = '" + request.getPartyId() + "'");
                }
            } else if ("case_reason_main_record".equals(tableName)) {
                List<String> packFieldList = new ArrayList<>();
                for (String field : fieldList) {
                    String packField = " string_agg ( " + field + ", ',' order by " + field + " ASC) as " + field;
                    packFieldList.add(packField);
                }
                fieldSql = StringUtils.join(packFieldList, ",");
                conditionSql = " from upcase." + tableName;
                whereSql = "case_id=" + "'" + request.getExecuteId() + "'" + "and status='1'";
            } else if ("sys_depart_param".equals(tableName)) {
                //关联的机构名称
                conditionSql = " from upcase." + tableName + " sdp left join execute.execute_main_info emi on  sdp.org_code=emi.handle_org_code";
                whereSql = "emi.execute_id=" + "'" + request.getExecuteId() + "'";
            } else {
                conditionSql = " from execute." + tableName;

            }
            Map<String, Object> dataMap = new HashMap<>();
            String sqlStr = "select " + fieldSql + conditionSql + " where " + whereSql + " limit 1";
            if (StringUtils.isNotEmpty(conditionSql)) {
                dataMap = cSourceDocCommonOperateMapper.getDataMap(sqlStr);
            }
            //组装参数值表
            if (ObjectUtil.isNotEmpty(dataMap)) {
                for (String field : fieldList) {
                    sourceDataMap.put(tableName + "." + field, dataMap.get(field) == null ? "" : dataMap.get(field).toString());
                }
            }
        }
        return sourceDataMap;
    }

    /**
     * 根据模板字段配置信息，组装查询所需要的字段，并组装成map格式
     *
     * @param sourceFieldInfos 源字段信息
     * @param request          请求
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/02/28
     */
    private Map<String, String> getExecuteTestDataMap(Map<String, Object> sourceFieldInfos, ExecuteDocCommonHtmlRequest request) {
        Map<String, String> sourceDataMap = new HashMap<>();
        Set<String> keySet = sourceFieldInfos.keySet();

        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(request.getExecuteId());
        String orgCode = executeMainInfo.getExecuteOrgCode();
        if (ObjectUtil.isEmpty(orgCode)) {
            new BusinessException("执行单位编码为空");
        }
        for (String tableName : keySet) {
            List<String> fieldList = JSONObject.parseArray(sourceFieldInfos.get(tableName).toString(), String.class);
            String fieldSql = StringUtils.join(fieldList, ",");
            String conditionSql = "";
            String whereSql = "case_source_id=" + "'" + request.getExecuteId() + "'";
            if ("case_main_info".equals(tableName)) {
                conditionSql = " from upcase." + tableName;
                whereSql = "id=" + "'" + request.getExecuteId() + "'";
            } else if ("case_parties_person_info".equals(tableName)
                    || "case_parties_legal_info".equals(tableName)
                    || "case_parties_record".equals(tableName)) {
                List<String> packFieldList = new ArrayList<>();
                for (String field : fieldList) {
                    String packField = " string_agg ( " + field + ", '、' order by party_type,create_time  desc ) as " + field;
                    packFieldList.add(packField);
                }
                fieldSql = StringUtils.join(packFieldList, ",");
                if ("case_parties_record".equals(tableName)) {
                    conditionSql = " from upcase." + tableName + " cpr ";
                } else {
                    conditionSql = " from upcase." + tableName + " left join upcase.case_parties_record cpr on cpr.party_id=" + tableName + ".id";
                }
                whereSql = "case_id=" + "'" + request.getExecuteId() + "'" + " and cpr.status='1' ";
                if (!ObjectUtils.isEmpty(request.getPartyId())) {
                    whereSql = whereSql.concat(" and cpr.party_id = '" + request.getPartyId() + "'");
                }
            } else if ("case_reason_main_record".equals(tableName)) {
                List<String> packFieldList = new ArrayList<>();
                for (String field : fieldList) {
                    String packField = " string_agg ( " + field + ", ',' order by " + field + " ASC) as " + field;
                    packFieldList.add(packField);
                }
                fieldSql = StringUtils.join(packFieldList, ",");
                conditionSql = " from upcase." + tableName;
                whereSql = "case_id=" + "'" + request.getExecuteId() + "'" + "and status='1'";
            } else if ("sys_depart_param".equals(tableName)) {
                conditionSql = " from upcase." + tableName;
                whereSql = "org_code=" + "'" + orgCode + "'";
            } else {
                if (tableName.contains("csource.")) {
                    conditionSql = " from " + tableName;
                    if ("csource.case_source_register_main_info".equals(tableName)) {
                        whereSql = "id=" + "'" + request.getExecuteId() + "'";
                    }
                    if ("csource.case_source_party_info".equals(tableName)) {
                        whereSql = "id=" + "'" + request.getPartyId() + "'";
                    }


                } else {
                    conditionSql = " from upcase." + tableName;
                }


            }
            Map<String, Object> dataMap = new HashMap<>();
            String sqlStr = "select " + fieldSql + conditionSql + " where " + whereSql + " limit 1";
            if (StringUtils.isNotEmpty(conditionSql)) {
                dataMap = cSourceDocCommonOperateMapper.getDataMap(sqlStr);
            }
            //组装参数值表
            if (ObjectUtil.isNotEmpty(dataMap)) {
                for (String field : fieldList) {
                    sourceDataMap.put(tableName + "." + field, dataMap.get(field) == null ? "" : dataMap.get(field).toString());
                }
            }
        }
        return sourceDataMap;
    }

    /**
     * 从文书管理 获取模板详情
     *
     * @param documentCatalogCode 文件目录的代码
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/02/26
     */
    public Map<String, Object> getTemplateDetail(String documentCatalogCode, String caseSourceId, String templateType) {
        //根据文书目录编码获取模板code
        String templateCode = getTemplateCodeByDocumentCatalogCode(documentCatalogCode, caseSourceId, null);

        Map<String, String> headers = HeaderUtil.headerInfo();

        Map<String, Object> paramsMap = new HashMap<>();
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("templateCode", templateCode);
        requestMap.put("templateType", templateType);
        String result = HttpUtil.createPost(url.concat(templateDetail)).addHeaders(headers).body(JSON.toJSONString(requestMap)).contentType("application/json").execute().body();
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {
                JSONObject data = JSON.parseObject(jsonObject.get("data").toString());
                //获取返回的html内容
                paramsMap.put("htmlContent", data.getString("standardFormTemplate"));
                paramsMap.put("templateFieldConfigs", data.getString("templateFieldConfigs"));
                paramsMap.put("sourceFieldInfos", data.getString("sourceFieldInfoMap"));
            } else {
                log.info("调用失败，result:" + result);
            }
        }
        return paramsMap;
    }

    /**
     * 获取转换生成pdf并上传到oss的地址
     *
     * @param pdfRequest pdf格式的请求
     * @return {@link String }
     * @author shishengyao
     * @date 2022/02/25
     */
    public Map<String, String> getConvertedPdfUrl(FillAndConvertToPdfRequest pdfRequest) {

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("templateCode", pdfRequest.getTemplateCode());
        paramMap.put("paramMap", pdfRequest.getParamMap());
        paramMap.put("templateType", pdfRequest.getTemplateType());
        String result = HttpClientUtil.executeRequest(url + uploadConvertedPdf, "POST", "application/json", paramMap);
        if (StringUtils.isNotBlank(result)) {
            JSONObject jsonObject = JSONObject.parseObject(result);
            if ("200".equals(jsonObject.get("code").toString())) {
                String dataResult = jsonObject.get("data").toString();
                JSONObject data = JSON.parseObject(dataResult);
                Map<String, String> resultMap = new HashMap<>();
                //文书地址
                resultMap.put("fileUrl", data.getString("fileUrl"));
                //生成文书base64
                resultMap.put("fileBase64", data.getString("fileBase64"));
                return resultMap;
            } else {
                throw new BusinessException(jsonObject.getString("message"));
            }
        } else {
            throw new BusinessException("文书生成服务网络异常");
        }
    }

    /**
     * 文件签章并上传到oss
     *
     * @param queryDto 查询dto
     * @return {@link Map<String, String> }
     * @author shishengyao
     * @date 2022/03/07
     */
    @Override
    public String dealFileSeal(FileSealInfoQueryDto queryDto) {
        queryDto.setFileType("pdf");
        queryDto.setFileTransferForm("1");
        queryDto.setFileBase64(queryDto.getFileBase64());
        queryDto.setAddSignTime(false);
        queryDto.setSealCode("");
        queryDto.setKey("签章处");
        queryDto.setSignType(4);
        queryDto.setSealCode("12");
        queryDto.setPosX(0);
        queryDto.setPosY(0);
        //签章
        Map<String, Object> fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
        if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
            log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
            throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
        }
        //获取pdf页码若2张以上，加盖骑缝章
        try {
            byte[] fileBytes = (byte[]) fileAfterSeal.get("fileBytes");
            InputStream ins = new ByteArrayInputStream(fileBytes);
            PdfReader pdfReader = new PdfReader(ins);
            int pages = pdfReader.getNumberOfPages();
            if (pages > 1) {
                queryDto.setFileType("pdf");
                queryDto.setFileTransferForm("1");
                String base64 = Base64.encodeBase64String(fileBytes);
                queryDto.setFileBase64(base64);
                queryDto.setKey("");
                queryDto.setSealCode("21");
                queryDto.setSignType(3);
                queryDto.setPosX(100);
                queryDto.setPosY(450);
                queryDto.setPosPage("1-" + pages);
                fileAfterSeal = fileSealProvinceUnifiedService.getFileAfterSeal(queryDto);
                if (ObjectUtil.isNotEmpty(fileAfterSeal.get("errorMsg"))) {
                    log.info("warn fileSealService,result:{}", fileAfterSeal.get("errorMsg"));
                    throw new BusinessException(fileAfterSeal.get("errorMsg").toString());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("系统异常:" + e.getMessage());
        }

        //上传签章后的文件到oss
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileBytes", fileAfterSeal.get("fileBytes"));
        jsonObject.put("fileType", "pdf");
        jsonObject.put("fileName", "");
        JSONObject parseObject = JSON.parseObject(HttpUtil.post(url + uploadBase64File, jsonObject.toString()));
        String cd = "code";
        int th = 200;
        if (parseObject.getInteger(cd) == th) {
            String url = parseObject.getJSONObject("data").getString("ossUrl");
            log.info("签章后地址：{}", url);
            return url;
        } else {
            log.info("warn receive sign file upload oss fail,result:{}", parseObject.toString());
            throw new BusinessException("签章后上传文件失败：" + jsonObject.getString("message"));
        }

    }

    /**
     * 描述：处理文书模板填充参数
     *
     * @param saveDto 保存dto
     * @return {@link Map<String, Object> }
     * @author shishengyao
     * @date 2022/03/10
     */
    private Map<String, Object> dealDocParamMap(ExecuteDocCommonOperateSaveDto saveDto) {
        // 送达地址确认书校验参数
        if (DocumentKindEnum.DOC_KIND_SDDZQRS.getCode().equals(saveDto.getDocumentKindCode())) {
            HashMap<String, Object> dataMap = saveDto.getDataMap();
            if (ObjectUtil.isNotEmpty(dataMap.get("SDDZQRS_SJHM"))) {
                if (!BaseUtil.validatePhoneNumber(dataMap.get("SDDZQRS_SJHM").toString())) {
                    throw new BusinessException("送达地址确认书手机号不正确");
                }
            }
        }
        Map<String, Object> paramMap = saveDto.getDataMap();
        if (ObjectUtil.isEmpty(paramMap.get(Constant.DOC_MAIN_HANDLE_SIGN_PIC)) ||
                ObjectUtil.isEmpty(Constant.DOC_ASSIST_HANDLE_SIGN_PIC)) {
            Map<String, Object> templateDetail = getTemplateDetail(saveDto.getDocumentCatalogCode(), saveDto.getExecuteId(), DocumentTemplateTypeEnum.getValueByCode(saveDto.getDocumentTemplateType()));
            //循环给自动填充的字段赋值
            Map templateFieldConfigs = JSON.parseObject(templateDetail.get("templateFieldConfigs").toString());
            //主办人、承办人签名
            String mainHandleSignPic = Constant.DOC_MAIN_HANDLE_SIGN_PIC;
            String assistHandleSignPic = Constant.DOC_ASSIST_HANDLE_SIGN_PIC;
            if (ObjectUtil.isNotEmpty(templateFieldConfigs.get(mainHandleSignPic)) ||
                    ObjectUtil.isNotEmpty(templateFieldConfigs.get(assistHandleSignPic))) {
                List<ExecuteHandlePersonRecord> personList = executeHandlePersonRecordService.getExecuteHandlePersonRecordList(saveDto.getExecuteId());
                personList.forEach(e -> {
                    if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType()) && ObjectUtil.isNotEmpty(templateFieldConfigs.get(mainHandleSignPic))) {
                        paramMap.put(mainHandleSignPic, e.getHandleSignPic());
                    } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(e.getHandlePersonType()) && ObjectUtil.isNotEmpty(templateFieldConfigs.get(assistHandleSignPic))) {
                        paramMap.put(assistHandleSignPic, e.getHandleSignPic());
                    }
                });
            }
        }
        return paramMap;
    }

    /**
     * 描述：【V1.0.0】文书文号生成
     *
     * @author tianrunjia
     * @date 2022-02-23
     */
    @WorkFlowRollAnnotation
    @Override
    public String getDocumentNumber(String executeId, String documentCatalogCode) {
        //“X机构”处填写制作法律文书的办案单位文号； X机构（ ）字〔 〕第 号
        //双执法主体切换
        /*List<CaseHandlePersonRecordVo> caseHandlePersonRecordVoList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseId);
        String handleDeptCode = caseHandlePersonRecordVoList.get(0).getHandleOrgCode();*/
        //String docDeptShort = configBusiParamDeptService.getConfigBusiParamDeptDetailByDeptCode(handleDeptCode).getDocumentDeptShort();
        //CaseMainInfo caseMainInfo = caseMainInfoMapper.selectByPrimaryKey(caseId);
        //CaseSourceRegisterMainInfo caseSourceRegisterMainInfo=caseSourceRegisterMainInfoMapper.selectByPrimaryKey(caseSourceId);
        /*SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseSourceRegisterMainInfo.getHandleOrgCode());
        String docDeptShort = sysDepartParam.getOrgShortName();*/


        ExecuteMainInfo executeMainInfo = executeMainInfoService.getByExecuteId(executeId);
        String orgCode = executeMainInfo.getHandleOrgCode();
        if (ObjectUtil.isEmpty(orgCode)) {
            throw new BusinessException("办案单位编码为空!");
        }
        //
        // 获取条线信息
        LineTerritoryInfoVo lineTerritoryInfoVo = sysDepartParamService.getLineInfoByOrgCodeAndLineCode(orgCode, "", executeMainInfo.getLineCode());
        String lineDocNumber = lineTerritoryInfoVo.getLineDocNumber();
        //获取（ ）内的内容 如立案、移案、询通、调证、登保决、鉴聘、申避决、听通、当罚决、不罚决、行罚决、行罚缴决、强执决、代履决、强执申、电送确、终决等；
        String numAbbreviation = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode).getDocumentNumberAbbreviation();
        //获取年度 “〔 〕”处填写年度
        String curretYear = "〔" + String.valueOf(LocalDate.now().getYear()) + "〕";
        //String curretYear = "〔1990〕";
        //“第 号”处填写4位自增序号的顺序编号。从缓存原子中获取
        String documentNumberKey = "UPCASE-DOCUMENTNUMBERKEY-" + curretYear;
        // long number = redisRepository.incr(documentNumberKey);
        long number = caseDocumentNumberSerialService.getNumber(executeId, "EXECUTE", documentCatalogCode, orgCode, "", "", curretYear);
        //String documentNumber = docDeptShort + "（" + numAbbreviation + "）" + curretYear + String.format("%06d", number);
        String documentNumber = lineDocNumber + numAbbreviation + curretYear + "第" + String.format("%06d", number) + "号";
        return documentNumber;
    }


    /*@Autowired
    public void setRedisRepository(RedisRepository redisRepository) {
        this.redisRepository = redisRepository;
    }*/


}
